package com.jie.controller;


import com.jie.utility.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/rear-end/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+substring;
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);

    }

    /**
     * 下载图片
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //输入流，通过输入流读取文件内容
        try {
            String value = (String) redisTemplate.opsForValue().get(name);
            ServletOutputStream outputStream = response.getOutputStream();
          if(StringUtils.isNotEmpty(value)){
              InputStream inputStream = decodeBase64ToImage(value);
              //设置响应文件类型
              response.setContentType("image/jpeg");
              int read;
              while ((read=inputStream.read())!=-1){
                  outputStream.write(read);

              }
              //关闭资源
              outputStream.close();
            return;
          }
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

            //设置响应文件类型
            response.setContentType("image/jpeg");
            int len=0;
            byte[] bytes=new  byte[1024];

            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                //刷新
                outputStream.flush();
            }
            redisTemplate.opsForValue().set(name,encodeImageToBase64(name));

            // 关闭 FileInputStream
            fileInputStream.close();
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
    }
    /**
     * 将图片内容编码为字符串
     * @param name 图片名
     * @return
     */
    public  String encodeImageToBase64(String name) {
        String filePath = basePath + name;
        File file = new File(filePath);
        // 检查文件是否存在
        if (file.exists()) {
            try {
                // 创建 FileInputStream 以读取文件内容
                FileInputStream fileInputStream = new FileInputStream(file);
                // 将 FileInputStream 中的数据读取到字节数组中
                byte[] data = new byte[(int) file.length()];
                fileInputStream.read(data);
                // 关闭 FileInputStream
                fileInputStream.close();
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encode(data).trim();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
           return "文件不存在";
        }
        return null;
    }

    /**
     * 将图片内容解码为输入流
     * @param base
     * @return
     */
    public static InputStream decodeBase64ToImage(String base) {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodeBytes = null;
        try {
            decodeBytes = decoder.decodeBuffer(base);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(decodeBytes);
    }
}
